/*
* @Author: root
* @Date:   2017-11-16 20:21:16
* @Last Modified by:   root
* @Last Modified time: 2017-11-18 20:26:33
*/
'use strict';
require('./index.css');
require('page/common/nav/index.js');
require('page/common/header/index.js');
var navSide         = require('page/common/nav-side/index.js');
var _utils          = require('util/util.js');
var _user           = require('service/user-service.js');
var templateIndex   = require('./index.string');
var page = {
	init : function(){
		this.onload();

		this.bindEvent();
	},
	onload  : function(){
		//初始化左侧菜单
		navSide.init({
		name:'user-center'
		});  
		//加载用户信息
		this.loadUserInfo();
	},
	//验证字段信息
	//sudo
	validateForm : function(formData){
		
		var result = {
			status : false,
			msg    : ''
		};
		//验证邮箱格式是否正确
		if(!_utils.validate(formData.email, 'email')){
            result.msg = '邮箱格式不正确';
            return result;
        }
        //手机格式是否正确
		if (!_utils.validate(formData.phone,'phone')) {
			result.msg = '手机格式不正确';
			return result;
		}
		//问题不能为空
		if (!_utils.validate(formData.question,'require')) {
			result.msg = '问题不能为空';
			return result;
		}
		//答案不能为空
		if (!_utils.validate(formData.answer,'require')) {
			result.msg = '答案不能为空';
			return result;
		}
		//通过验证，返回正确提示
		result.status = true;
		result.msg    = '验证通过';
		return result;
	},
	bindEvent : function(){
		var _this = this;
		$(document).on('click','.btn-submit',function(){
			var userInfo = {
				phone 	 : $.trim($("#phone").val()),
				email 	 : $.trim($("#email").val()),
				question : $.trim($("#question").val()),
				answer 	 : $.trim($("#answer").val()) 
			},
				validateResult = _this.validateForm(userInfo);

				


			if(validateResult.status){
				_user.updateUserInfo(userInfo,function(res,msg){
 				_utils.successTips(msg);
 				window.location.href = './user-center.html';
				},function(errMsg){
					_utils.errorTips(validateResult.msg);
				});
			}
			else {
				_utils.errorTips(validateResult.msg);
			}
		});
	},
	
	loadUserInfo : function(){
		var userHtml = '' ;
		_user.getUserInfo(function(res){
			
			userHtml = _utils.renderHtml(templateIndex, res);
		
			$('.panel-body').html(userHtml);
		},function(errMsg){
			_utils.errorTips(errMsg);
		});
	}
	
};
$(function(){
    page.init();
});